package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class WeChatServiceImpl implements WeChatService {


    private static final String REQUEST_URL ="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;


    //获取openid
    public String getOpenId(String code){
        //封装对象
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //调用微信接口
        String result = HttpUtil.get(REQUEST_URL, map);
        //解析返回的result对象(json格式)
        JSONObject entries = JSONUtil.parseObj(result);
        // 判断接口响应是否出错
        if(ObjectUtil.isNotEmpty(entries.getInt("errcode"))) {
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        //从对象中取得返回值openid
        String openid = entries.getStr("openid");
        return openid;
    }
    //获取token
    public String getToken(){
        //封装对象
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("grant_type","client_credential");
        //调用微信接口
        String s = HttpUtil.get(TOKEN_URL, map);
        //解析返回值
        JSONObject entries = JSONUtil.parseObj(s);
        if(ObjectUtil.isNotEmpty(entries.getInt("errcode"))) {
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        //返回token的值
        return entries.getStr("access_token");
    }
    //获取手机号
    public String getPhoneNumber(String code){
        //调用gettoken方法获取token
        String token = getToken();
        //拼接url地址
        String url = PHONE_REQUEST_URL + token;
        //封装请求对象
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        //发起请求并将map集合转换成json格式
        String post = HttpUtil.post(url, JSONUtil.toJsonStr(map));
        JSONObject entries = JSONUtil.parseObj(post);
        // 判断接口响应是否出错
        if(entries.getInt("errcode") != 0) {
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        //取出json对象中嵌套的值
        String phone = entries.getJSONObject("phone_info").getStr("phoneNumber");
        return phone;
    }
}
